package cn.lg.soar.system.biz.modules.auth.service;

import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.system.api.enums.RoleTypeEnum;
import cn.lg.soar.system.biz.config.SystemCacheKey;
import cn.lg.soar.system.biz.modules.auth.entity.Role;
import cn.lg.soar.system.biz.modules.auth.model.RoleSelectorDTO;
import cn.lg.soar.system.biz.modules.auth.model.RoleTree;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class RoleSelectorService {

    @Autowired
    private IRoleService service;

    public List<RoleSelectorDTO> ids(Collection<Long> ids) {
        return toDto(
                service.listByIds(ids, SystemCacheKey.ROLEID_TO_ROLE)
        );
    }

    public List<RoleSelectorDTO> query(String keyword, RoleTypeEnum[] types) {
        return toDto(
                service.page(
                        new Page<>(1, 500),
                        Wrappers.<Role>lambdaQuery()
                                .select(Role::getId, Role::getName, Role::getParentId, Role::getType)
                                .eq(Role::getDisabled, false)
                                .in(DataUtil.isValuable(types), Role::getType, (Object[]) types)
                                .like(Role::getName, keyword)
                ).getRecords()
        );
    }

    public List<RoleSelectorDTO> role(Long parentId) {
        List<RoleTree> tree = service.tree(parentId);
        return tree.stream().map(RoleSelectorDTO::from)
                .collect(Collectors.toList());
    }

    private List<RoleSelectorDTO> toDto(List<Role> roles) {
        return roles.stream()
                .map(RoleSelectorDTO::from)
                .collect(Collectors.toList());
    }
}
